<script lang="ts" setup>
import { generateCssVars } from '@vc/utils';
import {
  type EsgAnnouncementProps, getClassificationCode2, getCompanyEsgData
} from '../../../apis';
import { INIT_PARAMS, PAGE_SIZE } from '../../../constants';
import { useF9Context } from '../../../use/use-context';
import { INIT_TAB_STYLE } from '../../pollution-discharge-permits/constants';
import { useEsgReportTable } from '../use/useEsgReportTable';
import PageHeader from '../../../components/page-header.vue';

interface Props {
  /** 标题名称 */
  title: string;
  /** 标题 id */
  menuId: string;
  /** 数值 */
  count: number;
}

const { title, menuId, count } = defineProps<Props>();

let pageNum = $ref(1);
const { companyId } = useF9Context();
const requestParams = reactive<EsgAnnouncementProps>({
  id: companyId,
  classificationCode1: 300000,
  ...INIT_PARAMS,
  classificationCode2: ''
});

const { data: tabInfos } = useRequest(getClassificationCode2, {
  defaultParams: [companyId],
  onSuccess: (res) => {
    res[0].code = res
    .filter((item) => item.code)
    .map((item) => item.code)
    .join(',');
  
    requestParams.classificationCode2 = res[0].code;
  }
});

const {
  data: tableData,
  run,
  loading,
  error
} = useRequest(getCompanyEsgData, {
  manual: true
});

const { columns } = useEsgReportTable();

/** 翻页点击 */
const handleCurrentChange = (data) => {
  pageNum = data;
  run({ ...requestParams, pageNum });
};

const sortChange = (data) => {
  requestParams.sort = data.order;
};

watch(
  () => requestParams,
  (val) => {
    pageNum = 1;
    run({ ...val, pageNum });
  },
  {
    deep: true
  }
);

const activeTab = ref(0);

const handleTabChange = (data) => {
  requestParams.classificationCode2 = tabInfos.value?.[data]?.code;
};
</script>

<template>
  <page-header class="mt-18px mb-15px" :count="count" :title="title" :menuId="menuId" is-small />

  <vc-tabs :model-value="activeTab"
    :style="generateCssVars(INIT_TAB_STYLE, 'tabs')"
    @tab-change="handleTabChange"
    type="card" class="inline-block descriptions w-full">
    <vc-tab-pane v-for="(item, index) in tabInfos" :key="index"
      :label="item.name + '(' + (item.count || 0) + ')'" :name="index" />
  </vc-tabs>
  
  <vc-empty-fail @click="run({...requestParams, pageNum})" v-if="error" />
  <div class="container" v-else>
    <vc-table
      :loading="loading"
      :tableData="tableData?.pageData?.items"
      :columns="columns"
      :total="tableData?.pageData?.total"
      :pageSize="PAGE_SIZE"
      v-model:pageNum="pageNum"
      @page-change="handleCurrentChange"
      @sort-change="sortChange"
    />
  </div>
</template>
